package com.oms.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oms.dao.BaseDao;
import com.oms.dao.impl.UserDaoImpl;
import com.oms.domain.User;
import com.oms.service.UserService;
import com.oms.util.MD5Util;
import com.oms.util.POtoVOUtil;
import com.oms.util.SendMailUtil;
import com.oms.web.form.RegisteForm;
import com.sun.mail.smtp.SMTPSendFailedException;

@Transactional
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

	
    @Resource(name = "userDao")  
    public void setDao(BaseDao<User> dao) {  
        super.setDao(dao);  
    }
	
    @Resource(name = "userDao") 
	private UserDaoImpl userDaoImpl;
	
/*	public UserServiceImpl() {
		// TODO Auto-generated constructor stub
	}*/

	@Override
	public User findUserByEmail(String email) {
		String hql="from User user where user.email=?0";
		
		List<User> list=userDaoImpl.list(hql,email);
		
		if(list==null||list.isEmpty())
		{
			return null;
		}else if(list.get(0)!=null){
			User resultUser=list.get(0);
			System.out.println(resultUser.getName());
			return list.get(0);
		}else{
			return null;
		}
	}

	@Override
	public User findUserByName(String name) {
		String hql="from User user where user.name=?0";
		List<User> list=userDaoImpl.list(hql,name);
		if(list==null||list.size()==0||list.isEmpty())
		{
			return null;
		}else if(list.get(0)!=null){
			User resultUser=list.get(0);
			System.out.println(resultUser.getName());
			return list.get(0);
		}else{
			return null;
		}
	}
	
	@Override
	public Boolean registeUser(RegisteForm registeForm) {
		User userPo=(User) POtoVOUtil.copyObject(registeForm, User.class);
		Timestamp registeTime=new Timestamp(System.currentTimeMillis());
		
//		System.out.println(userPo.getPassword());
		
		userPo.setPassword(MD5Util.enCryptPassword(userPo.getPassword()));	//加密密码
		
		//设置数据表中的一些非空值
		userPo.setRole((Short.valueOf("0")));
		userPo.setLatestLogin(registeTime);
		userPo.setRegisteTime(registeTime);
		userPo.setPersonalInfoOpenExtent(Short.valueOf("0"));
		userPo.setAccountState(Short.valueOf("0"));
		userPo.setActiveCode(UUID.randomUUID().toString());
		userPo.setActiveState(false);
		userPo.setUserInfoLastUpdateTime(registeTime);
		userPo.setDeleteTag(false);
		
		userDaoImpl.save(userPo);
		
		String subject=registeForm.getName()+"乐玩社团网激活";	//激活邮件的标题
		String content=registeForm.getName()+
				"乐玩社团网的激活连接为:http://localhost:8080/organizationmanagement/userActive.do?activeCode="+userPo.getActiveCode();	//激活邮件的内容
		try {
			SendMailUtil.send(userPo.getEmail(), subject, content);
		} catch (AddressException|SMTPSendFailedException e) {
			e.printStackTrace();
			throw new RuntimeException("发送邮箱验证出错,错误信息为:"+e.getMessage());
		} catch (MessagingException e) {
			e.printStackTrace();
			throw new RuntimeException("发送的邮件内容出错，错误信息为:"+e.getMessage());
		}		
		return true;
	}

	@SuppressWarnings("null")
	@Override
	public User activeUser(String activeCode) {
		String hql="from User user where user.activeCode=?0";
		List<User> list=userDaoImpl.list(hql,activeCode);
		if(list==null||list.size()==0||list.isEmpty()){
			throw new RuntimeException("找回的集合为空，该注册码无效");
		}
		User user=list.get(0);
		if(user==null){
			throw new RuntimeException("找回的user为空，该注册码无效."+user.getName());
		}else if(user.getActiveState()==true){
			throw new RuntimeException("该用户已经激活过了");
		}else if(System.currentTimeMillis()-user.getRegisteTime().getTime()>1000*3600*24){
			throw new RuntimeException("该激活连接已超过24小时，已过期");
		}
		user.setActiveState(true);
		userDaoImpl.save(user);
		return user;
	}
	
	@Override
	public User loginByEmail(String email,String password){
		System.out.println("开始查询用户");
		String hql="from User user where user.email=?0 and user.password=?1";
//		String password1= MD5Util.encodeToHex(MD5Util.myEncryptMethod(password));
		System.out.println(password);
		List<User> list=userDaoImpl.list(hql, email ,password);
		if(list==null||list.isEmpty()){
			System.out.println("查询到的结果集为空");
			throw new RuntimeException("账号密码不正确");
		}
		User user=list.get(0);
		if(user==null){
			System.out.println("查询到的用户结果为空");
			throw new RuntimeException("账号密码不正确");
		}
		System.out.println("查询到该用户");
		return user;
	}

	@Override
	public void forgotPasswordByEmail(String email) {
		
		String hql="from User user where user.email=?0";
		
		List<User> list=userDaoImpl.list(hql,email);
		User resultUser=null;
		
		if(list==null||list.isEmpty())
		{
			throw new RuntimeException("1");
		}
		resultUser=list.get(0);
		System.out.println(resultUser.getName());
		//查看该账号是否已经激活(重置密码也生成一个激活码)
		if(!resultUser.getActiveState()){
			throw new RuntimeException("2");
		}
		//生成唯一验证码
		resultUser.setActiveCode(UUID.randomUUID().toString());
		Timestamp alterPasswordDeadline=new Timestamp(System.currentTimeMillis()+24*3600*1000);
		resultUser.setAlterPasswordDeadline(alterPasswordDeadline);
		userDaoImpl.update(resultUser);
		
		String subject=resultUser.getName()+"乐玩社团网密码重置";	//激活邮件的标题
		String content=resultUser.getName()+
				"乐玩社团网的激活连接为:http://localhost:8080/organizationmanagement/resetPasswordByEmail.do?resetCode="
				+resultUser.getActiveCode()+"  <br/>请在24小时内完成修改操作!";	//重置密码的邮件内容
		try {
			SendMailUtil.send(resultUser.getEmail(), subject, content);
		} catch (AddressException|SMTPSendFailedException e) {
			e.printStackTrace();
			throw new RuntimeException("发送邮箱验证出错,错误信息为:"+e.getMessage());
		} catch (MessagingException e) {
			e.printStackTrace();
			throw new RuntimeException("发送的邮件内容出错，错误信息为:"+e.getMessage());
		}		
	}
	
	@Override
	public User applyResetPawByEmail(String resetCode) {
		String hql="from User user where user.activeCode=?0";
		List<User> list=userDaoImpl.list(hql,resetCode);
		if(list==null||list.isEmpty()){
			throw new RuntimeException("1");	//找回的集合为空，该重置码无效
		}
		User user=list.get(0);
		if(user==null){
			throw new RuntimeException("2");	//找回的user为空，该重置码无效.
		}else if(!user.getActiveState()){
			throw new RuntimeException("3");	//该用户未激活
		}else if(System.currentTimeMillis()-user.getAlterPasswordDeadline().getTime()>0){
			throw new RuntimeException("4");	//该重置连接已超过24小时，已过期
		}
		return user;
	}
	
	@Override
	public User resetPassword(String resetCode, String password) {
		String hql="from User user where user.activeCode=?0";
		List<User> list=userDaoImpl.list(hql,resetCode);
		if(list==null||list.isEmpty()){
			throw new RuntimeException("1");	//找回的集合为空，该重置码无效
		}
		User user=list.get(0);
		if(user==null){
			throw new RuntimeException("2");	//找回的user为空，该重置码无效.
		}else if(!user.getActiveState()){
			throw new RuntimeException("3");	//该用户未激活
		}else if(System.currentTimeMillis()-user.getAlterPasswordDeadline().getTime()>0){
			throw new RuntimeException("4");	//该重置连接已超过24小时，已过期
		}
		user.setAlterPasswordDeadline(new Timestamp(System.currentTimeMillis()));
		user.setPassword(MD5Util.enCryptPassword(password));
		userDaoImpl.save(user);
		return user;
	}
	
	@Override
	public User findUserById(Integer id) {
		return userDaoImpl.findById(id);
	}

	@Override
	public void updateUser(User user) {
		userDaoImpl.update(user);
	}





}
